package com.taptech.doufu.services.offline;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.os.Handler;


public class OffLineDownRunnable implements Runnable {

	private OffLineInfoBean offLineInfoBean;
	private File file;
	private Context context;
	private OffLineDownLoader downLoader;
	private Handler handler;

	public OffLineDownRunnable(Handler handler, Context context, OffLineDownLoader downLoader,
			OffLineInfoBean offLineInfoBean, File file) {
		this.context = context;
		this.downLoader = downLoader;
		this.offLineInfoBean = offLineInfoBean;
		this.file = file;
		this.handler = handler;

	}

	@Override
	public void run() {
		try {
			URL url = new URL(offLineInfoBean.getOffline_url());
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			offLineInfoBean.setOffline_filemax(connection.getContentLength());
			InputStream inStream = connection.getInputStream();
			OutputStream output = new FileOutputStream(file);
			byte[] buffer = new byte[3*1024];
			int len = 0;
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				while ((len = inStream.read(buffer)) != -1) {
					Thread.sleep(300);
					downLoader.append(len);
					output.write(buffer,0,len);
				}
			} else {
				handler.sendMessageDelayed(handler.obtainMessage(0,"网络超时"),1000);
			}
			inStream.close();
			output.close();
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
			handler.sendMessageDelayed(handler.obtainMessage(0,"网络超时"),1000);
		}

	}
}
